﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace TimeCapsule
{
	public class ErrorMessage
	{
		int _code;
		string _msg, _title;
		
		public int Code { get { return _code; } }
		public string Message { get { return _msg; } set { _msg = value; } }
		public string Title { get { return _title; } set { _title = value; } }
	
		public ErrorMessage(int Code)
		{
			
		}
		
		public ErrorMessage(ErrorCode error)
		{
			Debug(string.Format("Error Code : {0}", error.ToString()));
			_code = (int)error;
			ToString(error, "");
		}
		
		public static void Set(ErrorMessage err)
		{
			if (HttpContext.Current.Items["Error"] == null)
				HttpContext.Current.Items.Add("Error", err);
			else
				HttpContext.Current.Items["Error"] = err;
		}
		
		public static void Set(ErrorCode code)
		{
			if (HttpContext.Current.Items["Error"] == null)
				HttpContext.Current.Items.Add("Error", new ErrorMessage(code));
			else
				HttpContext.Current.Items["Error"] = new ErrorMessage(code);
		}
		
		public static ErrorMessage Get()
		{
			ErrorMessage err = (ErrorMessage)HttpContext.Current.Items["Error"];
			return (err == null) ? new ErrorMessage(0) : err;
		}
		
		public static int GetCode()
		{
			ErrorMessage err = (ErrorMessage)HttpContext.Current.Items["Error"];
			return (err == null) ? 0 : err.Code;
		}
		
		public static bool IsError()
		{
			ErrorMessage err = (ErrorMessage)HttpContext.Current.Items["Error"];
			return (err != null && err.Code != 0);
		}
	
		public static void Clear()
		{
			HttpContext.Current.Items.Remove("Error");
		}
		
		public string ToString(ErrorCode error, string msg)
		{
			string rscName = "ErrorCode";
			try
			{
				_title = error.ToString();
				_msg = (string.IsNullOrEmpty(_msg) ? HttpContext.GetGlobalResourceObject(rscName, error.ToString()).ToString() : msg);
			}
			catch
			{
				_title = error.ToString();
				_msg = (string.IsNullOrEmpty(_msg) ? HttpContext.GetGlobalResourceObject(rscName, "Unknown").ToString() : msg);
			}
			
			return _msg;
		}
			
		[System.Diagnostics.Conditional("DEBUG")]
		public static void Debug(string msg)
		{
			System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(3, true);
			string method = sf.GetMethod().Name;
			string file = sf.GetFileName();
			int line  = sf.GetFileLineNumber();
			
			System.Diagnostics.Debug.Print("[{3} - {0} : {1}\n{2}", method, line, msg, file);
		}
	}
}
